Creating a Script in an HTML Document

You can create an entire script within the HTML document itself, that is, the script code is written inside the HTML document making it in-line with the HTML content. The script code is written between the <script> and </script> tags in the HTML document.

Depending on your requirements, you can place the <script> and </script> tags in either the <body> tag portion or the <head> tag portion of the HTML document. When you want the script to run while the Web page is loading in the Web browser, place the <script> and </script> tags in the body portion. On the other hand, if you want the script to run only when the user performs an action, such as clicking a link, then you can place the <script> and </script> tags in the head portion of the Web page.

Let’s do the following steps to create a script within the HTML document:


<!DOCTYPE html>
<html>
<head>
    <title>JavaScriptExample</title>
</head>
<body bgcolor=”pink”>
<center>
    <h1>JavaScript</h1>
    <script type=”text/javascript” language=”javascript”>
    document.write(“Creating a Script in an HTML Document”);
    </script>
</body>
</html>

In above code, the </script> and </script> tags are placed inside the <body> and </body> tags. This implies that the script is loaded in the Web browser at the same time as the Web page is loading. In the <script> tag, the type attribute is set to text/javascript and the language attribute is set to javascript. These two attributes convey to the Web browser that the subsequent content in the HTML document is a script that is written in JavaScript. The document.write(“Creating a Script in an HTML Document”) line is a JavaScript code, where document is an object and write is a method that allows you to display information on the Web page.

Note: you learn more about the document object and its methods later in the chapter.

Save the document with the name createScript.html and open with browser.

Note: There is no limit to the number of scripts that you can add in an HTML document.

Let’s now move on to understand how to use an external script file in an HTML document.